<template>
  <tm-app>
    <!-- #ifndef H5 -->
    <tm-navbar title="浙里资产"></tm-navbar>
    <!-- #endif -->
    <view>
      <view class="fix-top">
        <headers title="办事" />
        <tag tagSize="n" :taglist="WorkTypeTabs" :tagActive="data.tagActive" @btnClick="changeData" />
      </view>
      <tm-sheet :margin="[0]" v-if="data.isLoading">
        <tm-skeleton-line :height="50"></tm-skeleton-line>
        <tm-skeleton-line :height="50"></tm-skeleton-line>
        <tm-skeleton model="chat"></tm-skeleton>
        <tm-skeleton model="chat"></tm-skeleton>
        <tm-skeleton model="chat"> </tm-skeleton>
      </tm-sheet>
      <tm-scrolly class="from-content" v-else :_style="'height:88vh;margin-top:100px;'">
        <work-list :list="data.taskList" :tagActive="data.tagActive" v-if="data.taskList.length > 0"></work-list>
        <tm-sheet :margin="[0, 2]" v-else>
          <tm-result :showBtn="false" title="暂无数据" class="custom-work-result"></tm-result>
        </tm-sheet>
      </tm-scrolly>
      <!-- <scroll-view
        scroll-y="true"
        class="scroll-Y mt108"
        :refresher-enabled="true"
        @refresherrefresh="refresher"
        :refresher-triggered="data.triggered"
        v-else
      >
        <work-list
          :list="data.taskList"
          :tagActive="data.tagActive"
          v-if="data.taskList.length > 0"
        ></work-list>
        <tm-sheet :margin="[0, 2]" v-else>
          <tm-result
            :showBtn="false"
            title="暂无数据"
            class="custom-work-result"
          ></tm-result>
        </tm-sheet>
      </scroll-view> -->
    </view>
  </tm-app>
</template>

<script lang="ts" setup>
// #ifdef H5
import { getCurrentInstance } from 'vue'
import { useRoute } from 'vue-router'
// #endif
import { ref, reactive, onMounted } from 'vue'
import tag from '../../components/tag/index.vue'
import headers from '../../components/header/header.vue'
import workList from './components/workList.vue'
import { TaskTypeName } from '@/ts/core'
import { TabItems, TabItemsInfo } from '@/ts/base/model'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { TabItemsCode } from '@/ts/base/model'
import Common from '../../pages/home/common/common'
import CustomWork from './utils'
import { XWorkTask } from '../../ts/base/schema'
import orgCtrl from '../../ts/controller'
type DataType = {
  taskList: XWorkTask[]
  tagActive: string
  triggered: boolean
  isLoading: boolean
}

const data = reactive<DataType>({
  taskList: [],
  tagActive: 'todo',
  triggered: false,
  isLoading: true
})

const WorkTypeTabs = ref<TabItems[]>([])

onLoad(option => {
  /** 从门户跳转进来 */
  if (option && Object.values(TabItemsCode).includes(option.code)) {
    const routerParams: TabItems = {
      code: option.code,
      label: option.label,
      count: 0
    }
    changeData(routerParams)
  }
  loadWorkTypeTabs()
})

async function getList(taskType: TaskTypeName) {
  uni.showLoading({
    title: '数据加载中'
  })
  data.taskList = []
  let resultList: XWorkTask[] = []
  switch (taskType) {
    case '待办':
      {
        resultList = await CustomWork.loadTodos()
      }
      break
    case '已办':
    case '抄送':
    case '已发起':
    case '已完结':
      {
        resultList = await CustomWork.loadTasks(taskType, 0)
      }
      break

    default:
      resultList = []
      break
  }
  const newTasks = resultList.sort((a, b) => {
    return new Date(b.updateTime).getTime() - new Date(a.updateTime).getTime()
  })
  data.taskList = [...newTasks]
  uni.hideLoading()
  data.isLoading = false
}
async function changeData(item: TabItems) {
  data.tagActive = item.code
  data.isLoading = true
  if (item.label === '常用') {
    loadCommons()
  } else {
    getList(item.label as TaskTypeName)
  }
  uni.setStorageSync('taskType', item.label)
}

/** 加载常用 */
const loadCommons = async () => {
  uni.showLoading({
    title: '数据加载中'
  })
  const resultList = await Common.initPortal()
  data.taskList = resultList
  setTimeout(() => {
    uni.hideLoading()
    data.isLoading = false
  }, 1000)
}

onShow(() => {
  uni.$once('changeList', () => {
    getList(uni.getStorageSync('taskType') as TaskTypeName)
  })
})
// 加载各tag徽标数量
const loadWorkTypeTabs = async () => {
  let todoCount = 0
  let preloadTodos: XWorkTask[] = []
  try {
    preloadTodos = await CustomWork.loadTodos()
    todoCount = preloadTodos.length || 0
  } catch (error) {
    console.log(error)
  }
  const result = [
    {
      id: '1',
      label: TabItemsInfo.commons.label,
      code: TabItemsInfo.commons.code,
      allowEdit: true,
      count: 0
    },
    {
      id: '2',
      label: TabItemsInfo.todo.label,
      code: TabItemsInfo.todo.code,
      allowEdit: true,
      default: true,
      count: todoCount
    },
    {
      id: '3',
      label: TabItemsInfo.done.label,
      code: TabItemsInfo.done.code,
      allowEdit: true,
      count: 0
    },
    {
      id: '4',
      label: TabItemsInfo.alt.label,
      code: TabItemsInfo.alt.code,
      allowEdit: true,
      count: 0
    },
    {
      id: '5',
      label: TabItemsInfo.create.label,
      code: TabItemsInfo.create.code,
      allowEdit: true,
      count: 0
    },
    {
      id: '6',
      label: TabItemsInfo.end.label,
      code: TabItemsInfo.end.code,
      allowEdit: true,
      count: 0
    }
  ]

  WorkTypeTabs.value = result
  /** 初始化：默认标签直接复用已加载的待办，避免二次请求 */
  const initTag = result.find(item => item.code === data.tagActive)!
  if (initTag.code === TabItemsInfo.todo.code) {
    data.tagActive = initTag.code
    const newTasks = preloadTodos.sort((a, b) => {
      return new Date(b.updateTime).getTime() - new Date(a.updateTime).getTime()
    })
    data.taskList = [...newTasks]
    data.isLoading = false
  } else {
    changeData(initTag)
  }
}

onMounted(() => {
  orgCtrl.user.loadTeams().then(cohot => {
    cohot.forEach(iz => {
      iz.loadIdentitys()
      iz.loadMembers()
    })
  })
})
// #ifdef H5
onMounted(() => {
  const route = useRoute()
  const instance = getCurrentInstance()
  const queue = instance?.appContext.config.globalProperties.$queue
  if (queue) {
    queue.push({
      id: route.meta.id,
      title: route.meta.title,
      path: route.path
    })
  }
})
// #endif
</script>
<style lang="scss">
@import '../../common/style/global.scss';

.todo-list {
  display: flex;
  align-items: center;
  position: relative;
}

.flex-list {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.rg-time {
  position: absolute;
  right: 25px;
}

.fix-top {
  position: fixed;
  background: #fff;
  z-index: 1;
}

/*  #ifdef H5   */
.mt108 {
  padding-top: 108px;
  height: calc(100vh - 390rpx);
}

/*  #endif  */

/*  #ifndef H5   */
.mt108 {
  margin-top: 108px;
}

/*  #endif  */
.wd200 {
  width: 170px;
}

.custom-work-result {
  height: calc(100vh - 430rpx);
}
</style>
@/ts/core